window.addEventListener('load', function () {

  const btn = document.querySelector("#switch");

  chrome.storage.sync.get("linkOpen", ({ linkOpen }) => {
    btn.checked = linkOpen;
  });
  chrome.storage.sync.get(['record'], function(result) {
    console.log('Value currently is ' + result.record);
    document.getElementsByClassName("chapter")[0].innerHTML = `第${result.record || 0}章`
  });
  chrome.storage.sync.get(['bookName'], function(result) {
    console.log('Value currently is ' + result.bookName);
    document.getElementsByClassName("book")[0].innerHTML = result.bookName || '暂无'
  });

  btn.addEventListener("change", () => {
    if (btn.checked) {
      chrome.storage.sync.set({ linkOpen: true });
    } else {
      chrome.storage.sync.set({ linkOpen: false });
    }
    // 获取当前tab窗口
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
      chrome.scripting.executeScript({
        target: { tabId: tabs[0].id },
        func: refreshPage,
      });
    });
  });

  // 刷新页面
  function refreshPage() {
    window.location.reload();
  }


  var btn1 = document.querySelector('#btn');
  var fileInput = document.createElement('input');
  fileInput.type = 'file';
  fileInput.accept = '.txt';

  fileInput.addEventListener('change', function () {
    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function () {
      let bookName = file.name.replace(".txt",'')
      chrome.storage.sync.set({bookName: bookName}, function() {
        console.log('Value is set to ' + bookName);
        document.getElementsByClassName("book")[0].innerHTML = bookName
      });
      var chapters = [];
      var content = reader.result;
      var lines = content.split('\n');
      var currentChapter = { title: '', content: '' };

      lines.forEach(function (line) {
        if (line.includes('第') && line.includes('章')) { // 根据具体章节标题的格式进行判断，此处示例为包含"第"和"章"的行
          if (currentChapter.title !== '') {
            chapters.push(currentChapter);
          }
          currentChapter = { title: line, content: '' };
        } else {
          currentChapter.content += line + '\n';
        }
      });

      if (currentChapter.title !== '') {
        chapters.push(currentChapter);
      }
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { data: chapters });
      });
    };
    reader.readAsText(file);
  });

  btn1.addEventListener('click', function () {
    fileInput.click();
  });
});
